package com.go.where.manager.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.go.where.manager.dao.ActivityDao;
import com.go.where.manager.dao.GroupDao;
import com.go.where.manager.dao.OrderDao;
import com.go.where.manager.page.Pagination;
import com.go.where.manager.pojo.ActivityInfo;
import com.go.where.manager.pojo.GroupInfo;
import com.go.where.manager.pojo.OrderInfo;
import com.go.where.manager.pojo.user.UserInfoVO;
import com.go.where.manager.service.OrderService;

@Service("orderService")
public class OrderServiceImpl implements OrderService {

	@Resource(name = "orderDao")
	private OrderDao orderDao;
	@Resource
	private GroupDao groupDao;
	@Resource
	private ActivityDao activityDao;

	@Override
	public OrderInfo queryByPrimartKey(String cid) {
		OrderInfo order = orderDao.getByKey(cid);
		if ("2".equals(order.getActivityType())) {
			GroupInfo g = new GroupInfo();
			g.setOrderId(cid);
			GroupInfo gi = groupDao.queryByGroupId(g);
			if (gi != null) {
				String groupId = gi.getGroupId();
				order.setStartGroupTime(gi.getGroupTime());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("groupId", groupId);
				map.put("activityId", order.getActivityId());
				Integer currPeoples = groupDao.queryGroupTotalPerson(map);
				if (currPeoples != null) {
					order.setGroups(currPeoples);
				}
				ActivityInfo ai = activityDao.getByKey(order.getActivityId());
				if (ai != null) {
					order.setEndTime(ai.getEndTime());
				}
			}
		}
		return order;
	}

	@Override
	public Pagination<OrderInfo> queryPage(OrderInfo orderInfo) {
		Integer count = orderDao.totalCount(orderInfo);
		orderInfo.calculate();
		List<OrderInfo> list = orderDao.queryList(orderInfo);
		if (list != null && !list.isEmpty()) {
			for (OrderInfo order : list) {
				String orderId = order.getOrderId();
				GroupInfo g = new GroupInfo();
				g.setOrderId(orderId);
				if ("2".equals(order.getActivityType())) {
					GroupInfo gi = groupDao.queryByGroupId(g);
					if (gi != null) {
						String groupId = gi.getGroupId();
						order.setStartGroupTime(gi.getGroupTime());
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("groupId", groupId);
						map.put("activityId", order.getActivityId());
						Integer currPeoples = groupDao
								.queryGroupTotalPerson(map);
						if (currPeoples != null) {
							order.setGroups(currPeoples);
						}
					}
				}
			}
		}
		Pagination<OrderInfo> page = orderDao.queryPagination(count, list,
				orderInfo);
		return page;
	}

	@Override
	public int update(OrderInfo orderInfo, UserInfoVO currentUser) {
		orderInfo.setUpdateTime(new Date());
		orderInfo.setUserId(currentUser.getUserId());
		return orderDao.update(orderInfo);
	}

}
